package com.qqtech.qquan.mall.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.util.JsonUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.homemaking.model.HomemakingTypeVo;
import com.qqtech.qquan.mall.enums.MallCategoryStatusDictEnum;
import com.qqtech.qquan.mall.model.MallCategory;
import com.qqtech.qquan.mall.model.MallCategoryQuery;
import com.qqtech.qquan.mall.model.MallCategoryVo;
import com.qqtech.qquan.mall.service.MallCategoryService;
import com.qqtech.qquan.sys.controller.BaseAgentController;
import com.qqtech.qquan.sys.model.SysMenu;
import com.qqtech.qquan.sys.model.SysMenuVo;
import com.qqtech.qquan.user.model.UserAdmin;

@Controller
@RequestMapping(value = "/mall/category")
public class MallCategoryController extends BaseAgentController {
	@Resource
	private MallCategoryService mallCategoryService;
    
	@Override
	protected BaseService<MallCategory> getBaseService() {
		return mallCategoryService;
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "/mall/category-list";
	}
	
	@RequestMapping(value = "/tree", method = RequestMethod.POST)
	@ResponseBody
	public Result tree(HttpServletRequest request, HttpServletResponse response) {
		String parentId = request.getParameter("id");
		if (parentId == null) {
			parentId = "";
		}
		List<MallCategoryVo> list = mallCategoryService.queryListByParentId(parentId,null);
		List<Map<Object, Object>> tree = new ArrayList<Map<Object, Object>>();
		if (null != list) {
			for (int i = 0; i < list.size(); i++) {
				MallCategoryVo m = (MallCategoryVo) list.get(i);
				Map<Object, Object> node = new HashMap<Object, Object>();
				node.put("id", m.getCategoryId());
				node.put("text", m.getName());
				node.put("state", "closed");
				node.put("iconCls", "icon-item");
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("parentId", m.getParentId());
				node.put("attributes", attributes);
				tree.add(node);
			}
		}
		String json = JsonUtil.toJson(tree);
		try {
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(@RequestParam(required = false) String parentId, HttpServletRequest request,
			HttpServletResponse response) {
		if (StringUtil.isNotBlank(parentId)) {
			MallCategoryVo parent = mallCategoryService.getByCategoryId(parentId);
			request.setAttribute("parent", parent);
		}
		return "/mall/category-update";
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result doAdd(MallCategoryVo mallCategoryVo, HttpServletRequest request, HttpServletResponse response) {
		Result ret = new Result();
		if (mallCategoryVo == null) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtils.isBlank(mallCategoryVo.getName())) {
				ret.addErr("请输入分类名称");
			}
			if (mallCategoryVo.getStatus() == null) {
				ret.addErr("请输入状态");
			}
		}
		if (ret.checkForm()) {
			Timestamp now = TimeUtil.now();
			MallCategory mallCategory = new MallCategory();
			mallCategory.setName(mallCategoryVo.getName());
			mallCategory.setStatus(mallCategoryVo.getStatus());
			mallCategory.setImg("");
			mallCategory.setAdImg("");
			mallCategory.setNewAt(now);
			if (mallCategory.getOidx() == null) {
				mallCategory.setOidx(mallCategoryService.getMaxOidxByParentId(mallCategoryVo.getParentId()) + 1);
			}
			if (StringUtil.isBlank(mallCategoryVo.getParentId())) {
				mallCategory.setParentId("0");
				mallCategory.setLevel(1);
				//生成id
				Integer categoryId = Integer.valueOf(mallCategory.getLevel()+"000");
				// 最后一条记录
				MallCategoryQuery q = new MallCategoryQuery();
				q.setParentId(mallCategory.getParentId());
				PageOrder page = new PageOrder(Direction.DESC, "id");
				Pageable pageKit = new PageKit(1, 1, new PageOrder(Direction.DESC, "id"));
				List<MallCategoryVo> lastList = mallCategoryService.queryList(q, pageKit);
				if (lastList != null && !lastList.isEmpty()) {
					MallCategoryVo last = lastList.get(0);
					categoryId = Integer.valueOf(last.getCategoryId()) + 1;
				}
				mallCategory.setCategoryId(categoryId.toString());
			} else {
				mallCategory.setParentId(mallCategoryVo.getParentId());
				MallCategoryVo parent = mallCategoryService.getByCategoryId(mallCategoryVo.getParentId());
				mallCategory.setLevel(parent.getLevel() + 1);
				//生成id,父级id+当前id
				Integer categoryId = Integer.valueOf(mallCategory.getLevel()+"000");
				// 最后一条记录
				MallCategoryQuery q = new MallCategoryQuery();
				q.setParentId(mallCategory.getParentId());
				Pageable pageKit = new PageKit(1, 1, new PageOrder(Direction.DESC, "id"));
				List<MallCategoryVo> lastList = mallCategoryService.queryList(q, pageKit);
				if (lastList != null && !lastList.isEmpty()) {
					MallCategoryVo last = lastList.get(0);
					categoryId = Integer.valueOf(last.getCategoryId().replace(last.getParentId(), "")) + 1;
				}
				mallCategory.setCategoryId(mallCategory.getParentId() + categoryId.toString());
			}
			mallCategory.setUpdAt(now);
			if(StringUtil.isNotBlank(mallCategoryVo.getImg())){
				mallCategory.setImg(mallCategoryVo.getImg());
			}
			if(StringUtil.isNotBlank(mallCategoryVo.getAdImg())){
				mallCategory.setAdImg(mallCategoryVo.getAdImg());
			}
			mallCategoryService.insert(mallCategory);
		}
		return ret;
	}
	
	@RequestMapping(value = "/update/{categoryId}", method = RequestMethod.GET)
	public String update(@PathVariable String categoryId, HttpServletRequest request, HttpServletResponse response) {
		MallCategoryVo mallCategoryVo = mallCategoryService.getByCategoryId(categoryId);
		request.setAttribute("mallCategoryVo", mallCategoryVo);
		if (null != mallCategoryVo && null != mallCategoryVo.getParentId()) {
			MallCategoryVo parent = mallCategoryService.getByCategoryId(mallCategoryVo.getParentId());
			request.setAttribute("parent", parent);
		}
		return "/mall/category-update";
	}
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Result doUpdate(MallCategoryVo mallCategoryVo) {
		Result ret = new Result();
		if (mallCategoryVo == null || StringUtil.isBlank(mallCategoryVo.getCategoryId())) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(mallCategoryVo.getName())) {
				ret.addErr("请输入分类名称");
			}
			if (mallCategoryVo.getStatus() == null) {
				ret.addErr("请输入状态");
			}
			if (mallCategoryVo.getOidx() == null) {
				ret.addErr("请输入排序");
			}
		}
		if (ret.checkForm()) {
			MallCategory update = new MallCategory();
			update.setCategoryId(mallCategoryVo.getCategoryId());
			update.setName(mallCategoryVo.getName().trim());
			update.setStatus(mallCategoryVo.getStatus());
			update.setOidx(mallCategoryVo.getOidx());
			update.setImg(mallCategoryVo.getImg());
			update.setAdImg(mallCategoryVo.getAdImg());
			update.setUpdAt(TimeUtil.now());
			mallCategoryService.updateByCategoryId(update);
		}
		return ret;
	}
	
	/**
	 * 获取子分类
	 * @param parentId
	 * @return
	 */
	@RequestMapping(value = "/findChildren")
	@ResponseBody
	public Result findChildren(String parentId) {
		Result result = new Result();
		if (parentId != null) {
			List<MallCategoryVo> list = mallCategoryService.queryListByParentId(parentId, MallCategoryStatusDictEnum.VALID.getCode());
			result.put("childrenList", list);
		}
		return result;
	}
	
	@RequestMapping(value = "/imgUpload", method = RequestMethod.GET)
	public String imgUpload(Model model) {
		return "/mall/category-imgUpload";
	}
}
